# collectmsg.pl
# vi: et sw=2
#
# CollectMsg
# Copyright (C) 2009  Harry Karvonen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
# Author:  Harry Karvonen <harry_karvonen@gmail.com>
#

#
# Version: 0.65
#
# Usage:
# Activate /collect <TAB>
# /collect msgcollection
#

use strict;

# Variables
my $active = 0;
my $debug = 0;
my $channel = "";
my $name = "Collect messages";
my $version = "v0.65";

Xchat::register($name, $version, "Collect all messages to current tab");

Xchat::hook_server("PRIVMSG", "collect_msg");
Xchat::hook_command("collect", "collect", "Set collection tab");
Xchat::hook_command("collect_active", "acollect", "Set collection on/off");
Xchat::hook_command("collect_tab", "tcollect", "Set collection tab");
Xchat::hook_command("collect_debug", "debug", "Set debug on/off (0 = off)");

sub tcollect {
  $channel = $_[0][1];
}

sub acollect {
  $active = $_[0][1];
  $active =~ s/.*on.*/1/i;
  $active =~ s/.*off.*/0/i;
}

sub debug {
  $debug = $_[0][1];
  $debug =~ s/.*on.*/1/i;
  $debug =~ s/.*off.*/0/i;
}

sub collect {
  $channel = $_[0][1];
  $active = 1;

  Xchat::command("DIALOG $channel");
  Xchat::print("Collect: Actived", $channel);
  return Xchat::EAT_NONE;
}

sub collect_msg {

  if ($active != 1) {
    return Xchat::EAT_NONE;
  }
  # ARGS
  # raw sender
  my $arg0 = $_[0][0];
  # msg channel
  my $arg2 = $_[0][2];
  # raw message
  my $arg3 = $_[1][3];

  my $user;
  my $msg;
  my $msg_channel = $arg2;

# Variabels

  # Sender
  if ($arg0 =~ /^:(\S+)!.+$/) {
    $user = $1;
  }

  # message
  if ($arg3 =~ /^:(.+)$/) {
    $msg = $1;
  }

  Xchat::set_context(Xchat::find_context($channel));

  if ($debug >= 1) {
    Xchat::print("Arg0: $arg0");
    Xchat::print("Msg channel: $msg_channel");
    Xchat::print("Channel: $channel");
    Xchat::print("USER: $user MSG: $msg");
    Xchat::print("Context: " . Xchat::get_context());

  }

  if ($user !~ m/$arg2/i) {
    Xchat::emit_print("Channel Message", "$user", "[$msg_channel]: $msg");
  }

  # Msg isn't our active channel bring it to it
#  if ($my_channel ne $channel && $msg =~/$nick/) {
#    Xchat::print("**$channel** $user: $msg", $my_channel);
#  }
 
  return Xchat::EAT_NONE;
}

Xchat::print("Plugin $name $version loaded successfully");
